package com.baidu.customview.widget.viewgroup;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;

import com.baidu.customview.R;
import com.baidu.customview.utils.MetricsUtils;

/**
 * Created by Kvin on 2016/1/7.
 */
public class DivideLineGridView extends GridView {
    private Paint paint;
    private int lineColor;

    //height
    private int baseH;
    private int baseW;
    private int rows;
    private int screenW;

    public DivideLineGridView(Context context) {
        super(context);
    }

    public DivideLineGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }


    public DivideLineGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DivideLineGridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    //use for draw divideLine
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        int n = getChildCount();
        int columns = 0;
        View v;
        if (n > 0) {
            v = getChildAt(0);
            baseH = v.getBottom() - v.getTop();//get every box metrics
            baseW = v.getRight();
            //columns = screenW / baseW;//get columns
            columns = getNumColumns();
            rows = n % columns == 0 ? n / columns : n / columns + 1;//get rows
        }
        //draw columns line
        for (int i = 1; i < columns; i++) {
            canvas.drawLine(baseW * i, 0, baseW * i, baseH * rows, paint);
        }
        //draw rows line
        for (int i = 1; i < rows; i++) {
            canvas.drawLine(0, baseH * i, screenW, baseH * i, paint);
        }
    }

    private void init(Context context, AttributeSet attrs) {
        paint = new Paint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DivideLineGridView);
        lineColor = typedArray.getColor(R.styleable.DivideLineGridView_lineColor, Color.BLACK);
        typedArray.recycle();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(1);
        paint.setColor(lineColor);
        screenW = MetricsUtils.winMetrics(context).widthPixels;
    }
}
